# gozerbot/aliases.py
#
#

""" 
    command aliases. this module contains the aliases of commands. aliases
    are stored in the gozerdata/aliases.new json file. 

"""

__status__ = "seen"

## gozerbot imports

from gozerbot.persist.persist import Persist
from gozerbot.datadir import datadir
from gozerbot.utils.locking import lockdec

# basic import

import os
import thread

## locks

aliaslock = thread.allocate_lock()
aliaslocked = lockdec(aliaslock)

## aliasreverse function

def aliasreverse(what):
    """ get the reverse of an alias. """
    for i, j in aliases.data.iteritems():
        if what == j: return i

## aliascheck function

def aliascheck(ievent):
    """ check if alias is available. """
    try:
        cmnd = ievent.txt.split()[0]
        alias = aliases.data[cmnd]
        ievent.txt = ievent.txt.replace(cmnd, alias, 1)
        ievent.alias = alias
        ievent.aliased = cmnd
    except (IndexError, KeyError): pass

## aliassave function

@aliaslocked
def aliassave():
    """ save aliases to json file. """
    aliases.save()

### aliasset function

@aliaslocked
def aliasset(fromm, to):
    """ set an alias. """
    aliases.data[fromm] = to

## aliasdel function

@aliaslocked
def aliasdel(fromm):
    """ delete an alias. """
    try: del aliases.data[fromm] ; return 1
    except KeyError: pass

## aliasget function

def aliasget(fromm):
    """ retrieve an alias. """
    if aliases.data.has_key(fromm): return aliases.data[fromm]

## defines

aliases = Persist(datadir + os.sep + 'aliases.new', init=False)
if not aliases.data: aliases.data = {}
